import {createContext, useEffect, useMemo, useState} from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";

interface UserInfoType {
    userid: string,
    token: string,
    refreshToken: string,
    expiresTime: number,
    localStorageTime: number,

    deptNamesStr: string,
    nickname: string,
}

interface UserInfoContextType {
    userInfo: UserInfoType,
    accessToken: string,
    refreshToken: string,
    isLoading: boolean,

    setUserInfo: (v: UserInfoType) => void,
    setAccessToken: (v: string) => void,
    setRefreshToken: (v: string) => void,
}

export const UserInfoContext = createContext<UserInfoContextType>({} as UserInfoContextType);

export function UserInfoProvider(props) {
    const [userInfo, setUserInfo] = useState('')
    const [accessToken, setAccessToken] = useState('')
    const [refreshToken, setRefreshToken] = useState('')
    const [isLoading, setIsLoading] = useState(true);

    const contextValue = useMemo<UserInfoContextType>(() => ({
        userInfo,
        accessToken,
        refreshToken,
        isLoading,
        setUserInfo,
        setAccessToken,
        setRefreshToken,
    }), [userInfo, accessToken, refreshToken, isLoading])

    async function init() {
        const userInfo = JSON.parse(await AsyncStorage.getItem('userInfo') ?? '');
        const accessToken = await AsyncStorage.getItem('accessToken');
        const refreshToken = await AsyncStorage.getItem('refreshToken');

        setUserInfo(userInfo);
        setAccessToken(accessToken ?? '');
        setRefreshToken(refreshToken ?? '');

        setIsLoading(false);
    }

    async function checkToken() {
        const userInfo = JSON.parse(await AsyncStorage.getItem('userInfo') ?? '');
        const accessToken = await AsyncStorage.getItem('accessToken');
        const refreshToken = await AsyncStorage.getItem('refreshToken');

    }

    useEffect(() => {
        init();
        checkToken();
    }, [])

    return (
        <UserInfoContext.Provider value={contextValue}>
            {props.children}
        </UserInfoContext.Provider>
    );
}